#include "Mystdio.h"

_FILE *_fopen(const char *filename, const char *flag)
{
	assert(filename);
	assert(flag);

	int fd = -1;
	int f = 0;

	if(strcmp(flag, "w") == 0)
	{
		f = (O_CREAT|O_WRONLY|O_TRUNC);
		fd = open(filename, f, _FILE_MODE);
	}
	else if(strcmp(flag, "a") == 0)
	{
		f = (O_CREAT|O_WRONLY|O_APPEND);
		fd = open(filename, f, _FILE_MODE);
	}
	else if(strcmp(flag, "r") == 0)
	{
		f = O_RDONLY;
		fd = open(filename, f);
	}
	else
	{
		return NULL;
	}

	if(fd == -1) return NULL;

	_FILE *fp = (_FILE*)malloc(sizeof(_FILE));
	if(fp == NULL) //打开失败
	{
		perror("Mystdio.h::malloc");
		return NULL;
	}
	 

	fp->fileno = fd;
        fp->flag = FFLUSH_ALL;
	fp->out_pos = 0;			

	return fp;
}

int _fwrite(_FILE *filename, const char *s, int len)
{
	//先将需要写入的内容放进缓冲区中
	memcpy(&filename->outbuffer[filename->out_pos], s, len);
	filename->out_pos += len;

	//判断刷新方式 将数据刷新到文件缓冲区
	if(filename->flag&FFLUSH_NOW)
	{
		if(filename->out_pos != 0)
		{
			write(filename->fileno, filename->outbuffer, filename->out_pos);
			filename->out_pos = 0;
		}
	}
	else if(filename->flag&FFLUSH_LINE)
	{
		//缓冲区数据:"abcd\n"
		if(filename->outbuffer[filename->out_pos - 1] == '\n') //不考虑其他情况
		{	write(filename->fileno, filename->outbuffer, filename->out_pos);
			filename->out_pos = 0;
		}
	}
	else if(filename->flag&FFLUSH_ALL)
	{
		if(filename->out_pos == SIZE)
		{
			write(filename->fileno, filename->outbuffer, filename->out_pos);
			filename->out_pos = 0;
		} //使用括号括起来，不然filename->out_pos会清零，缓冲区就没数据了
	}
	else
	{
		return -1;
	}

	return len; //返回实际写入文件流中的字节数
}

void _fflush(_FILE *filename)
{
	if(filename->out_pos != 0)
	{
		write(filename->fileno, filename->outbuffer, filename->out_pos);

		filename->out_pos = 0;
	}
}

void _fclose(_FILE *filename)
{
	if(filename != NULL)
	{
		_fflush(filename);
		close(filename->fileno);
		free(filename);
		filename = NULL;
	}
}












